<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               v-model="form"
               ref="crud"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad"
               :before-open="beforeOpen">
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   v-if="permission.business_add"
                   @click="startEdit({},'add')">新 增
        </el-button>

        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.business_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button size="small" circle type="warning" plain icon="el-icon-view"
                   @click.stop="view(scope.row)"></el-button>
        <el-button size="small" type="primary" plain icon="el-icon-edit-outline" circle
                   @click.stop="startEdit(scope.row,'edit')"></el-button>
        <el-button size="small" type="danger" icon="el-icon-delete" circle plain
                   @click.stop="deleteOne(scope.row)"></el-button>
      </template>
    </avue-crud>


    <div v-if="editByStep">
      <el-dialog append-to-body
                 :visible.sync="editByStep"
                 width="60%"
                 :before-close="editByStepClose">
        <span slot="title">
          <el-steps :active="active" simple style="margin-right: 40%">
          <el-step title="基础信息" icon="el-icon-view"></el-step>
          <el-step title="属性字段" icon="el-icon-tickets"></el-step>
          <el-step title="主题表信息" icon="el-icon-document-copy"></el-step>
        </el-steps>

        </span>
        <div v-if="0==active">
          <avue-form ref="form"
                     v-model="form"
                     :option="editOption">
            <template slot="datasourceId" slot-scope="scope">
              <el-select v-model="form.datasourceId" placeholder="请选择 数据源" @change="getTables">
                <el-option v-for="item in dataSourceDict"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </template>
          </avue-form>
        </div>
        <div v-if="1==active">
          <el-tabs v-model="showValue" type="card" @tab-click="handleClick">
            <el-tab-pane
              :key="item.name"
              v-for="(item) in tabNames"
              :label="item.name"
              :name="item.name"
            >
              <avue-crud :option="tableOption"
                         :table-loading="tableLoading"
                         :data="item.data"
                         :page.sync="tablePage"
                         v-model="tableForm"
                         :ref="item.name"></avue-crud>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div v-if="2==active">
          <avue-crud :option="finishOption"
                     :table-loading="finishLoading"
                     :data="tabNames"
                     :page.sync="finishPage"
                     v-model="finishForm"
                     :key="qualityTestingTimeFieldKey"
                     ref="finishCrud">
            <template slot="qualityTestingTimeFieldForm" slot-scope="{row}">
              <el-select v-model="row.qualityTestingTimeField" placeholder="请选择 质检时间字段"
                         @focus="getQualityTestingTimeFieldDic(row)" size="small"
                         @change="changeQualityTestingTimeField">
                <el-option v-for="item in qualityTestingTimeFieldDic"
                           :key="item.name"
                           :label="item.name"
                           :value="item.name"></el-option>
              </el-select>
            </template>
          </avue-crud>
        </div>
        <el-footer style="text-align: right;margin-top: 15px">
          <el-button type="primary"
                     icon="el-icon-bottom"
                     size="small"
                     v-if="type=='add'&&0==active"
                     @click="addAttribute"
          >下一步
          </el-button>
          <el-button type="primary"
                     icon="el-icon-check"
                     size="small"
                     v-if="type=='edit'&&0==active"
                     @click="updateAttribute"
          >下一步
          </el-button>
          <el-button icon="el-icon-circle-close"
                     size="small"
                     plain
                     v-if="0==active"
                     @click="editByStepClose"
          >取 消
          </el-button>
          <el-button type="primary"
                     icon="el-icon-top"
                     size="small"
                     v-if="1==active"
                     @click="backToAdd"
          >上一步
          </el-button>
          <el-button type="primary"
                     icon="el-icon-bottom"
                     size="small"
                     v-if="1==active"
                     @click="active=2"
          >下一步
          </el-button>
          <el-button type="primary"
                     icon="el-icon-top"
                     size="small"
                     v-if="2==active"
                     @click="active=1"
          >上一步
          </el-button>
          <el-button type="primary"
                     icon="el-icon-check"
                     size="small"
                     v-if="2==active"
                     @click="submit"
          >提 交
          </el-button>
        </el-footer>
      </el-dialog>
    </div>

    <div v-if="viewDetail">
      <el-dialog title="查 看"
                 append-to-body
                 :visible.sync="viewDetail" width="60%" :before-close="viewClose">
        <model_view :modelForm="modelForm"
        ></model_view>
        <div slot="footer" class="dialog-footer"></div>
      </el-dialog>
    </div>
  </basic-container>
</template>

<script>
import {mapGetters} from "vuex";
import {
  getList,
  getTableNames,
  getTableStructure,
  saveBusinessModelInfo,
  deleteModelInfos,
  deleteOneModelInfo,
  getThemeInfosByTables,
  updateModelInfo,
  modelDetail
} from "@/api/data_quality/business_model"
import {businessModelList} from "@/api/tool/datasource"
import model_view from "./model_view";
import {validatenull} from "../../../util/validate";

export default {
  name: "index",
  components: {model_view},
  data() {
    const modelNameValidate = (rule, value, callback) => {
      if (/^(?!_)[a-zA-Z_\u4e00-\u9fa5]/.test(value)) {
        callback();
      } else {
        callback(new Error("只能包含中文、英文和下划线，且不能以下划线开头！"))
      }
    };
    const titleValidate = (rule, value, callback) => {
      if (/^[a-zA-Z][a-zA-Z_0-9]/.test(value)) {
        callback();
      } else {
        callback(new Error("只能以字母开头，可拼接数字和下划线！"))
      }
    };
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        saveBtn: false,
        cancelBtn: false,
        delBtn: false,
        updateBtn: false,
        indexLabel: '序号',
        addTitle: '基础信息',
        editBtn: false,
        addBtn: false,
        column: [
          {
            label: "模型名称",
            prop: "modelName",
            rules: [{
              required: true,
              message: "请输入模型名称",
              trigger: "blur"
            }, {
              validator: modelNameValidate,
              trigger: "blur"
            }]
          },
          {
            label: "模型代码",
            prop: "modelCode",
            rules: [{
              required: true,
              message: "请输入模型代码",
              trigger: "blur"
            }]
          },
          {
            label: "关联表数",
            prop: "associatedNumber",
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: "创建时间",
            prop: "createTime",
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: "统计类型",
            prop: "statisticalType",
            type: 'select',
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=statisticalType",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            rules: [{
              required: true,
              message: "请选择统计类型",
              trigger: "blur"
            }],
            hide: true,
          },
          {
            label: "数据源",
            prop: "datasourceId",
            formslot: true,
            hide: true,
            rules: [{
              required: true,
              message: "请选择数据源",
              trigger: "blur"
            }],
          },
          {
            label: "数据表",
            prop: "dataTables",
            dicData: [],
            type: 'select',
            multiple: true,
            dataType: 'string',
            props: {
              label: "name",
              value: "value"
            },
            span: 24,
            rules: [{
              required: true,
              message: "请选择数据表",
              trigger: "blur"
            }],
            hide: true,
          },
          {
            label: "描述",
            prop: "remark",
            span: 24,
            minRows: 3,
            hide: true,
            type: "textarea",
            maxlength: 1000,
            showWordLimit: true
          },
        ]
      },
      editOption: {
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        saveBtn: false,
        cancelBtn: false,
        delBtn: false,
        updateBtn: false,
        indexLabel: '序号',
        addTitle: '基础信息',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模型名称",
            prop: "modelName",
            rules: [{
              required: true,
              message: "请输入模型名称",
              trigger: "blur"
            }, {
              validator: modelNameValidate,
              trigger: "blur"
            }]
          },
          {
            label: "模型代码",
            prop: "modelCode",
            rules: [{
              required: true,
              message: "请输入模型代码",
              trigger: "blur"
            }]
          },
          {
            label: "关联表数",
            prop: "associatedNumber",
            display: false,
          },
          {
            label: "创建时间",
            prop: "createTime",
            display: false,
          },
          {
            label: "统计类型",
            prop: "statisticalType",
            type: 'select',
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=statisticalType",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            rules: [{
              required: true,
              message: "请选择统计类型",
              trigger: "blur"
            }],
            hide: true,
          },
          {
            label: "数据源",
            prop: "datasourceId",
            formslot: true,
            hide: true,
            rules: [{
              required: true,
              message: "请选择数据源",
              trigger: "blur"
            }],
          },
          {
            label: "数据表",
            prop: "dataTables",
            dicData: [],
            type: 'select',
            multiple: true,
            dataType: 'string',
            props: {
              label: "name",
              value: "value"
            },
            rules: [{
              required: true,
              message: "请选择数据表",
              trigger: "blur"
            }],
            hide: true,
            span: 24,
          },
          {
            label: "描述",
            prop: "remark",
            span: 24,
            minRows: 3,
            hide: true,
            type: "textarea",
            maxlength: 1000,
            showWordLimit: true
          },
        ]
      },
      data: [],
      dataSourceDict: [],
      newAddBusinessModel: {},
      tabNames: [],
      showValue: '',
      addOrEdit: false,
      addOrEditTitle: '',
      tableOption: {
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        selection: false,
        dialogClickModal: false,
        saveBtn: false,
        addBtn: false,
        delBtn: false,
        columnBtn: false,
        refreshBtn: false,
        indexLabel: '序号',
        header: false,
        editTitle: '修改描述',
        editBtnText: '修改描述',
        menuWidth: 150,
        cellBtn: true,
        menu: false,
        column: [
          {
            label: "中文名称",
            prop: "chName",
          },
          {
            label: "英文名称",
            prop: "name",
          },
          {
            label: "字段类型",
            prop: "type",
          },
          {
            label: "字段长度",
            prop: "dataSize",
          },
          {
            label: "小数位",
            prop: "digits",
          },
          {
            label: "是否允许为空",
            prop: "nullable",
            type: 'radio',
            editDisplay: false,
            dicData: [
              {
                label: '是',
                value: 1
              },
              {
                label: '否',
                value: 0
              },
            ],
          },
          {
            label: "默认值",
            prop: "defaultValue",
          },
          {
            label: "是否唯一",
            prop: "ifUnique",
            type: 'radio',
            dicData: [
              {
                label: '是',
                value: 1
              },
              {
                label: '否',
                value: 0
              },
            ],
          },
          {
            label: "字段描述",
            prop: "remark",
            span: 24,
            cell: true,
            width: 200,
          },
        ]
      },
      finishOption: {
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        selection: false,
        dialogClickModal: false,
        saveBtn: false,
        addBtn: false,
        delBtn: false,
        columnBtn: false,
        refreshBtn: false,
        indexLabel: '序号',
        header: false,
        menuWidth: 150,
        labelWidth: 130,
        menu: false,
        cellBtn: true,
        column: [
          {
            label: "表名",
            prop: "name",
          },
          {
            label: "主题表名称",
            prop: "title",
            rules: [{
              required: true,
              message: "请输入模型名称",
              trigger: "blur"
            }, {
              validator: titleValidate,
              trigger: "blur"
            }],
            cell: true,
          },
          {
            label: "质检时间字段",
            prop: "qualityTestingTimeField",
            cell: true,
            formslot: true,
            rules: [
              {
                required: true,
                message: "请选择质检时间字段",
                trigger: "blur"
              }
            ],
          },
          {
            label: "标题",
            prop: "remarks",
            cell: true,
          },
        ]
      },
      tableLoading: false,
      tablePage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      finishPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      currentTable: '',
      allTablesInfo: [],
      toFinish: false,
      finishTitle: '',
      finishLoading: false,
      finishForm: {},
      viewDetail: false,
      modelForm: {},
      tableForm: {},
      type: '',
      editByStep: false,
      active: 0,
      qualityTestingTimeFieldDic: [],
      qualityTestingTimeFieldKey: 0,
    }
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.business_add, false),
        viewBtn: this.vaildData(this.permission.business_view, false),
        delBtn: this.vaildData(this.permission.business_delete, false),
        editBtn: this.vaildData(this.permission.business_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  created() {
    businessModelList().then(res => {
      this.dataSourceDict = res.data.data;
    })
  },
  methods: {
    changeQualityTestingTimeField() {
      this.qualityTestingTimeFieldKey += 1;
    },
    getQualityTestingTimeFieldDic(row) {
      row.qualityTestingTimeField = '';
      let dic = [];
      row.data.forEach(item => {
        if (item.type == 'DATETIME' || item.type == 'DATE' || item.type == 'TIMESTAMP') {
          dic.push(item);
        }
      })
      this.qualityTestingTimeFieldDic = dic;
    },
    startEdit(row, type) {
      this.editByStep = true;
      this.type = type;
      this.form = row;
      if (type == 'edit') {
        getTableNames(this.form.datasourceId).then(res => {
          let dataTables = this.findObject(this.editOption.column, "dataTables");
          dataTables.dicData = res.data.data;
          this.allTablesInfo = res.data.data;
        })
      }
    },
    editByStepClose() {
      this.editByStep = false;
      this.active = 0;
      this.type = '';
    },
    beforeOpen(done, type) {
      if (type == 'edit') {
        getTableNames(this.form.datasourceId).then(res => {
          let dataTables = this.findObject(this.option.column, "dataTables");
          dataTables.dicData = res.data.data;
          this.allTablesInfo = res.data.data;
        })
      }
      this.type = type;
      done();
    },
    deleteOne(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return deleteOneModelInfo(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return deleteModelInfos(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    view(row) {
      modelDetail(row.id).then(res => {
        this.modelForm = res.data.data;
        this.viewDetail = true;
      })
    },
    viewClose() {
      this.viewDetail = false;
    },
    submit() {
      let flg = true;
      this.tabNames.forEach(item => {
        if (flg) {
          flg = item.title != null && item.title != '' && item.title.length > 0 && /^(?!_)[a-zA-Z_\u4e00-\u9fa5]/.test(item.title)&&!validatenull(item.qualityTestingTimeField);
        }
      })
      if (flg) {
        this.newAddBusinessModel.allTablesInfo = this.tabNames;
        if (this.type == 'add') {
          saveBusinessModelInfo(this.newAddBusinessModel).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          })
        } else {
          updateModelInfo(this.newAddBusinessModel).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          })
        }
        this.editByStepClose();
      }else {
        this.$message({
          type: "warning",
          message: "请完善表格信息!"
        });
      }
    },
    backToAdd() {
      this.active = 0;
      this.form = JSON.parse(JSON.stringify(this.newAddBusinessModel));
    },
    handleClick(tab) {
      this.currentTable = tab.name;
    },
    updateAttribute(params = {}) {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          let tablesNames = this.form.dataTables.split(",");
          this.form.associatedNumber = tablesNames.length;
          this.newAddBusinessModel = JSON.parse(JSON.stringify(this.form));
          this.showValue = tablesNames[0];
          getThemeInfosByTables(Object.assign(params, this.newAddBusinessModel)).then(res => {
            this.tabNames = res.data.data;
            this.tabNames.forEach(tabName => {
              tabName.$cellEdit = true;
              if (tabName.remarks == null || tabName.remarks == '' || tabName.remarks.length == 0) {
                this.allTablesInfo.forEach(item => {
                  if (tabName.name == item.name) {
                    tabName.remarks = item.remarks;
                  }
                })
              }
              tabName.data.forEach(meta => {
                meta.$cellEdit = true;
              })
            })
          })
          this.currentTable = tablesNames[0];
          this.active = 1;
          done();
          // this.addOrEdit = true;
          // this.addOrEditTitle = '设置属性字段';
        }
      })
    },
    addAttribute() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          let tablesNames = this.form.dataTables.split(",");
          this.form.associatedNumber = tablesNames.length;
          this.newAddBusinessModel = JSON.parse(JSON.stringify(this.form));
          this.showValue = tablesNames[0];
          let tabs = [];
          tablesNames.forEach(item => {
            let table = {};
            table.name = item;
            table.title = item;
            table.data = [];
            table.$cellEdit = true;
            if (item != this.showValue) {
              getTableStructure(this.newAddBusinessModel.datasourceId, item).then(res => {
                table.data = res.data.data;
                table.data.forEach(item => {
                  item.$cellEdit = true;
                })
              })
            }
            tabs.push(table);
          })
          this.tabNames = tabs;
          getTableStructure(this.newAddBusinessModel.datasourceId, tablesNames[0]).then(res => {
            this.tabNames[0].data = res.data.data;
            this.tabNames[0].data.forEach(item => {
              item.$cellEdit = true;
            })
            this.currentTable = tablesNames[0];
            this.active = 1;
            done();
          })
          this.tabNames.forEach(tabName => {
            this.allTablesInfo.forEach(item => {
              if (tabName.name == item.name) {
                tabName.remarks = item.remarks;
              }
            })
          })
        }
      })

    },
    getTables(datasourceId) {
      getTableNames(datasourceId).then(res => {
        let dataTables = this.findObject(this.editOption.column, "dataTables");
        dataTables.dicData = res.data.data;
        this.allTablesInfo = res.data.data;
      })
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
}
</script>

<style scoped>
/deep/ .el-steps--simple {
  padding: 0 !important;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0);
}

/deep/ .el-step__title.is-process {
  font-weight: 700;
  color: #409EFF;
}

/deep/ .el-step__head.is-process {
  color: #409EFF;
  border-color: #303133;
}

/deep/ .el-step__title.is-finish {
  color: #67C23A;
}

/deep/ .el-step__head.is-finish {
  color: #67C23A;
  border-color: #67C23A;
}
</style>
